package com.example.juccode.juc01threadpool.demo04;

import com.example.juccode.juc01threadpool.demo04.Task.RunableTask;

import java.time.LocalTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @description: 定时任务，延时任务，周期性循环执行
 * @date 2025/11/4 14:17
 */
public class Demo06 {
    public static void main(String[] args) {
        /**
         * scheduleWithFixedDelay 间隔时间为周期
         * scheduleAtFixedRate    固定时间为周期
         */
        //创建任务
        RunableTask runableTask = new RunableTask();
        //创建调度任务
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        //输出当前时间
        System.out.println("当前时间：" + LocalTime.now());
        //提交任务
        ScheduledFuture<?> future = scheduledThreadPool.scheduleAtFixedRate(runableTask, 1, 1, TimeUnit.SECONDS);
        try {
            //使当前线程休眠5秒种
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //取消任务
            future.cancel(false);
            //关闭线程池0
            scheduledThreadPool.shutdown();
        }
    }
}
